package com.voxel.sense.infomsg.module.taskfrag;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.example.com.common.app.PresenterFragment;
import com.example.com.common.view.EmptyView;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.interfaces.listener.OnCustomItemClickListener;
import com.voxel.sense.infomsg.module.common.VRecyclerFrag;
import com.voxel.sense.infomsg.module.map.MapActivity;
import com.voxel.sense.infomsg.module.task.check.CheckTaskActivity;
import com.voxel.sense.infomsg.module.task.execution.TaskResultActivity;
import com.voxel.sense.infomsg.module.task.list.TaskListActivity;
import com.voxel.sense.infomsg.module.task.list.TaskListAdapter;
import com.voxel.sense.infomsg.module.task.list.TaskListContract;
import com.voxel.sense.infomsg.module.task.list.TaskListPresenter;
import com.voxel.sense.infomsg.module.task.overdue.OverdueTaskListActivity;
import com.voxel.sense.infomsg.module.task.send.SendTaskActivity;
import com.voxel.sense.infomsg.module.task.send.SendTaskContract;
import com.voxel.sense.infomsg.utils.GPSUtils;
import com.voxel.sense.infomsg.view.decoration.LinearItemDecoration;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.response.TaskInfoEntity;
import cyy.example.com.facotry.share.SPEngine;

public class TaskListFragment extends VRecyclerFrag<TaskListContract.Presenter,TaskInfoEntity.ObBean > implements TaskListContract.View<TaskInfoEntity.ObBean> {

    @Override
    public RecyclerAdapter<TaskInfoEntity.ObBean> getRecyclerViewAdapter() {
        return mAdapter;
    }

    @Override
    public void onAdapterDataChanged() {

    }

    @Override
    public void showEmptyView(String desc, boolean btnVisible) {

    }

    @Override
    public void onShowNoMore(boolean b) {

    }

    @Override
    public void onRefreshFinish() {
        refresh_layout.finishRefresh();
    }

    @Override
    public void onLoadMoreFinish() {
        refresh_layout.finishLoadMore();
    }

    @Override
    protected TaskListContract.Presenter initPresenter() {
        return new TaskListPresenter(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_task_list2;
    }


    @BindView(R.id.titlebar)
    TextTitleBar titlebar;
    @BindView(R.id.recycle_view)
    RecyclerView recycle_view;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.empty_view)
    EmptyView empty_view;
    @BindView(R.id.fl_btn)
    FloatingActionButton fl_btn;

    private TaskListAdapter mAdapter;
    private int mChangeItemPosition = -1; //记录下点击接受任务的item位置，用以恢复及刷新
    private TaskInfoEntity.ObBean mCurrentItemData;


    public static void show(Context context) {
        context.startActivity(new Intent(context, TaskListActivity.class));
    }





    @Override
    protected void initData() {
        super.initData();

        titlebar.setTitleText("任务列表");
        titlebar.setLeftVisible(false);
        titlebar.setRightVisible(false);
        recycle_view.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new TaskListAdapter();
        LinearItemDecoration linearItemDecoration = new LinearItemDecoration(R.drawable.recycle_divider_10dp);
        linearItemDecoration.setDrawFirstItem(true).setDrawVerticalModelLeftAndRightBorder(true,true);
        recycle_view.addItemDecoration(linearItemDecoration);
        recycle_view.setAdapter(mAdapter);
        empty_view.triggerOk();
        empty_view.bind(refresh_layout);

        refresh_layout.autoRefresh();//第一次进入触发自动刷新

        //根据权限设置派发按钮
        String distributing = SPEngine.getSPEngine().getUserInfo().getDistributing();
        if (Constants.NO_TASK_DISPATCH_PERMI.equals(distributing)) {
            fl_btn.setVisibility(View.GONE);
        } else {
            fl_btn.setVisibility(View.VISIBLE);

        }

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doLoadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                mPresenter.doLoadData();
            }
        });

//        titlebar.setRightTextAndLis("失败任务", new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                OverdueTaskListActivity.show(getContext());
//            }
//        });

        //初始化item的各种点击事件
        listItemClickEvent();
        jumpMapEvent();
        acceptTaskEvent();
        mAdapter.setDeleteClickListener(new OnCustomItemClickListener<TaskInfoEntity.ObBean>() {
            @Override
            public void onClick(View view, TaskInfoEntity.ObBean data, int position) {
                String user_id = SPEngine.getSPEngine().getUserInfo().getUser_id();
                if (user_id.equals(data.getFromId())) {
                    mPresenter.doDeleteTask(data.getTaskNumber(),data.getTaskId(),data.getTaskType(),data.getCompanyId(),data.getTaskStatu());
                }
            }
        });
    }


    private void listItemClickEvent() {
        mAdapter.setListener(new RecyclerAdapter.AdapterListenerImpl<TaskInfoEntity.ObBean>() {
            @Override
            public void onItemClick(RecyclerAdapter.ViewHolder holder, TaskInfoEntity.ObBean bean) {
                super.onItemClick(holder, bean);
                String taskStatu = bean.getTaskStatu();
                String user_id = SPEngine.getSPEngine().getUserInfo().getUser_id();
                if (Constants.TASK_ACTION_TYPE.equals(taskStatu) || Constants.TASK_CHECK_NOT_PASS.equals(taskStatu)) {
                    TaskResultActivity.show(getContext(), bean.getUploadForm(), bean.getTaskNumber(), bean.getTaskId(), bean.getOperatorType());
                } else if (Constants.TASK_FINISH_TYPE.equals(taskStatu)) {
                    CheckTaskActivity.show(getContext(), bean.getTaskNumber(), bean.getTaskId(), bean.getOperatorType());
                } else if (Constants.TASK_UNACCEPT_TYPE.equals(taskStatu) && user_id.equals(bean.getFromId())) {
                    SendTaskActivity.show(getContext(), SendTaskContract.ALTER_TASK, bean.getTaskNumber(), bean.getTaskId());
                }
            }
        });
    }

    /**
     * 导航按钮点击事件
     */
    private void jumpMapEvent() {
        mAdapter.setLocationClickEvent(new OnCustomItemClickListener<TaskInfoEntity.ObBean>() {
            @Override
            public void onClick(View view, TaskInfoEntity.ObBean data, int position) {
                try {
                    double latitude = Double.parseDouble(data.getLatitude());
                    double longitude = Double.parseDouble(data.getLongitude());
                    double[] doubles = GPSUtils.bd09_To_Gcj02(latitude, longitude);
                    MapActivity.show(getContext(), data.getCompanyName(), doubles[0], doubles[1]);
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }
        });
    }

    //接收任务事件
    private void acceptTaskEvent() {
        mAdapter.setSwitchClickEvent(new OnCustomItemClickListener<TaskInfoEntity.ObBean>() {
            @Override
            public void onClick(View view, TaskInfoEntity.ObBean data, int position) {
                mCurrentItemData = data;
                mChangeItemPosition = position;
                mPresenter.doTakeTask(data.getTaskId(), data.getTaskNumber());
            }
        });
    }

    @OnClick(R.id.fl_btn)
    void onClickEvent(View v) {
        if (v.getId() == R.id.fl_btn) {
            //跳转派发任务
            SendTaskActivity.show(getContext(), SendTaskContract.SEND_TASK);
        }
    }




    @Override
    public void onRefreshTaskStatu(String statu, String taskId) {
        if (mCurrentItemData != null) {
            mCurrentItemData.setTaskStatu(statu);
            mAdapter.notifyItemChanged(mChangeItemPosition);
            mCurrentItemData = null;
        }
    }
}
